package com.lzl.artisan.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzl.artisan.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;

public class BaseController {

    @Autowired
    HttpServletRequest req;

    /**
     * 获取页面
     * @return
     */
    public Page getPage() {
        int current = ServletRequestUtils.getIntParameter(req, "current", 1);
        int size = ServletRequestUtils.getIntParameter(req, "size", 10);

        return new Page(current, size);
    }

    Long getUserId(){
        String jwt = req.getHeader("token");
        if (StringUtils.isEmpty(jwt)){
            throw new RuntimeException("token不存在");
        }

        Claims claim = null;
        try {
            claim = JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (claim == null) {
            throw new JwtException("token 异常");
        }
        if (JwtUtil.isTokenExpired(claim)) {
            throw new JwtException("token已过期");
        }
        Long userId = Long.valueOf(claim.getSubject());
        return userId;
    }

}
